<template>
	<view class="container">
		<view class="form-item">
			<label>姓名</label>
			<input type="nickname" placeholder="请输入姓名" @input="updateName" />
		</view>
		<view class="form-item">
			<label>性别</label>
			<radio-group @change="updateSex">
				<label class="radio">
					<radio value="男" checked /><text>男</text>
				</label>
				<label class="radio">
					<radio value="女" /><text>女</text>
				</label>
			</radio-group>
		</view>
		<view class="form-item">
			<label>电话</label>
			<input type="number" placeholder="请输入电话" @input="updatePhone" />
		</view>
		<view class="form-item">
			<label>所在城市</label>
			<position-picker @update-region="regionChange"></position-picker>
		</view>
		??????????所在小区??????????
		<view class="form-item">
			<label>详细地址</label>
			<input type="text" placeholder="请输入详细地址" @input="updatePosition" />
		</view>
		<view class="form-item">
			<label>服务范围</label>
			<picker @change="serviceChange" :range="serviceArray">
				<view style="padding: 20rpx;background-color: white;">{{ service }}</view>
			</picker>
		</view>
		<view class="form-item">
			<label>选择模块</label>
			<picker @change="moduleChange" :range="moduleArray">
				<view style="padding: 20rpx;background-color: white;">{{ module }}</view>
			</picker>
		</view>

		<view class="form-item">
			<label>机构标签</label>
			<view>
				<checkbox-group class="block" @change="changeCheckbox">
					<view v-for="item in checkboxData" :key="item.value">
						<checkbox :value="item.label"></checkbox>
						<text>{{item.label}}</text>
					</view>
				</checkbox-group>
			</view>
		</view>
		<view class="form-item">
			<label>法人姓名</label>
			<input type="nickname" placeholder="请输入姓名" @input="updateLegalPersonName" />
		</view>
		<view class="form-item">
			<label>法人身份证号</label>
			<input type="idcard" placeholder="请输入身份证号" @input="updateLegalPersonIdCard" />
		</view>
		<view class="form-item">
			<label>请上传身份证反正面照片</label>
			<!-- <view class="front" @tap="frontUpLoad">
				<image :src="frontImage" mode="aspectFit"></image>
			</view>
			<view class="back" @tap="backUpLoad">
				<image :src="backImage" mode="aspectFit"></image>
			</view> -->
			<uni-section title="只选择图片" type="line">
				<view class="example-body">
					<uni-file-picker limit="2" title="最多选择2张图片" @select="handleIdSelect"
						@delete="handleIdDelete"></uni-file-picker>
				</view>
			</uni-section>
		</view>
		<view class="form-item">
			<label>商户名称</label>
			<input type="text" placeholder="请输入商户名称" @input="updateShopName" />
		</view>
		<view class="form-item">
			<label>营业执照编码</label>
			<input placeholder="请输入营业执照" @input="updateLicense" />
		</view>
		<view class="form-item">
			<label>请上传营业执照</label>
			<!-- <view class="front" @tap="licenseUpLoad">
				<image :src="licenseImage" mode="aspectFit"></image>
			</view> -->
			<uni-section title="只选择图片" type="line">
				<view class="example-body">
					<uni-file-picker limit="1" title="最多选择1张图片" @select="handleLicenseSelect"
						@delete="handleLicenseDelete"></uni-file-picker>
				</view>
			</uni-section>
		</view>
		<view class="form-item">
			<label>开户行</label>
			<input type="text" placeholder="请输入银行名称" @input="updateBankName" />
		</view>
		<view class="form-item">
			<label>银行卡号</label>
			<input placeholder="请输入银行卡号" @input="updateBankCard" />
		</view>
		<!-- 		<view class="form-item">
			<label>银行卡号</label>
			<view class="front" @tap="bank">
				<image src="@/static/images/user/id_front.jpg" mode="aspectFit"></image>
			</view>
		</view> -->
		<!-- <view class="form-item">
			<label>申请理由</label>
			<textarea placeholder="请输入申请理由"></textarea>
		</view> -->
		<!-- <uni-section title="只选择图片" type="line">
			<view class="example-body">
				<uni-file-picker limit="9" title="最多选择9张图片"></uni-file-picker>
			</view>
		</uni-section> -->
		<uni-section title="选择任意文件" type="line">
			<label>附件上传</label>
			<view class="example-body">
				<uni-file-picker limit="5" file-mediatype="all" title="最多选择5个文件" @select="handleFileSelect"
					@delete="handleFileDelete"></uni-file-picker>
			</view>

		</uni-section>
		<button type="primary" @click="submitForm" @tap="submit">提交申请</button>
		<button type="primary" @click="test">提交申请</button>
	</view>
</template>

<script setup>
	import {
		defineComponent
	} from 'vue';
	import http from '../../utils/http';
	const serviceArray = ref(['全国', '本省', '本市', '本小区'])
	const service = ref("请选择服务范围")



	const moduleArray = ref(['教培团购', '社区服务', '家政服务'])
	const module = ref("请选择模块")
	const checkedArr = ref([]) //复选框选中的值
	const checkboxData = ref([{
			'value': 0,
			'label': '早教'
		},
		{
			'value': 1,
			'label': '英语'
		},
		{
			'value': 2,
			'label': '语文'
		},
		{
			'value': 3,
			'label': '数学'
		},
	])
	// 身份证
	const frontImage = ref("../../static/images/user/id_front.jpg")
	const backImage = ref("../../static/images/user/id_back.jpg")
	const licenseImage = ref("../../static/images/user/id_front.jpg")

	// 提取字段
	const applicationContent = ref({
		applicationId: "",
		applicationTime: "",
		applicationType: "shop",
		currentType: getApp().globalData.user.identity,
		openid: getApp().globalData.user.openid, // 商家的openid
		name: '', // 姓名
		sex: '男', // 性别
		phone: '', // 电话
		region: '', // 所在城市
		position: '', // 详细地址
		longitude: '', // 经度
		latitude: '', // 纬度
		service: '', // 服务范围
		module: '', // 选择模块
		tags: '', // 机构标签
		legalPersonName: '', // 法人姓名
		legalPersonIdCard: '', // 法人身份证号
		shopName: '', // 商户名称
		license: '', // 营业执照编码
		bankName: '', // 开户行
		bankCard: '', // 银行卡号
		idImage: [],
		licenseImage: "",
		files: [],
		applicationStatus:"pending"

	});
	const image = ref({
		idCard: [], //身份证正反面照片
		license: "", // 营业执照照片
		files: [], // 附件 最多5个
	})
	// 联系人姓名
	function updateName(e) {
		applicationContent.value.name = e.target.value;
	}
	// 性别
	function updateSex(e){
		applicationContent.value.sex = e.target.value;
	}
	// 联系人电话
	function updatePhone(e) {
		applicationContent.value.phone = e.target.value;
	}
	// 所在区域
	function regionChange(e) {
		// console.log("position", e[0] + "-" + e[1] + "-" + e[2])
		applicationContent.value.region = e[0] + "-" + e[1] + "-" + e[2]
	}
	// 详细地址
	function updatePosition(e) {
		applicationContent.value.position = e.target.value;
	}
	// 服务范围
	function serviceChange(e) {
		service.value = serviceArray.value[e.detail.value]
		applicationContent.value.service = serviceArray.value[e.detail.value]
	}
	// 选择模块
	function moduleChange(e) {
		module.value = moduleArray.value[e.detail.value]
		applicationContent.value.module = moduleArray.value[e.detail.value]
	}
	// 机构标签
	function changeCheckbox(e) {
		checkedArr.value = e.detail.value
		applicationContent.value.tags = checkedArr.value.join(',');
	}

	function updateLegalPersonName(e) {
		applicationContent.value.legalPersonName = e.target.value;
	}

	function updateLegalPersonIdCard(e) {
		applicationContent.value.legalPersonIdCard = e.target.value;
	}
	//身份证正面照片
	function handleIdSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.idCard.push(e.tempFiles[i])
		}

	}

	function handleIdDelete(e) {
		console.log("delete", e)
		image.value.idCard.splice(e.index, 1); // 移除数组中对应的文件
	}

	function updateShopName(e) {
		applicationContent.value.shopName = e.target.value
	}

	function updateLicense(e) {
		applicationContent.value.license = e.target.value
	}

	function handleLicenseSelect(e) {
		image.value.license = e.tempFiles
	}

	function handleLicenseDelete(e) {
		image.value.license = e.tempFiles
	}

	function updateBankName(e) {
		applicationContent.value.bankName = e.target.value
	}

	function updateBankCard(e) {
		applicationContent.value.bankCard = e.target.value
	}

	function handleFileSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.files.push(e.tempFiles[i])
		}
	}

	function handleFileDelete(e) {
		image.value.files.splice(e.index, 1); // 移除数组中对应的文件
	}

	// 上传文件函数
	async function uploadFile(file, fileType) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:8080/utils/upLoadFile',
				filePath: file.path,
				name: 'file', // 文件字段名
				formData: {
					"filename": generateApplicationId(true, file),
					"applicationId": applicationContent.value.applicationId,
					"type": "shopApplication"
				},
				success: (uploadRes) => {
					const res = JSON.parse(uploadRes.data).data;
					if (fileType === 'idCard') {
						applicationContent.value.idImage.push(res)
					} else if (fileType === 'license') {
						applicationContent.value.licenseImage = res;
					} else if (fileType === 'file') {
						applicationContent.value.files.push(res);
					}
					resolve();
				},
				fail: (error) => {
					console.log('上传失败', error);
					reject(error);
				}
			});
		});
	}

	function generateApplicationId(flag, file) {
		const now = new Date();
		const year = now.getFullYear().toString().padStart(4, '0'); // 获取年份并转换为四位数
		const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并转换为两位数
		const day = now.getDate().toString().padStart(2, '0'); // 获取日期并转换为两位数
		const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并转换为两位数
		const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并转换为两位数
		const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒并转换为两位数
		const milliseconds = now.getMilliseconds().toString().padStart(3, '0'); // 获取毫秒并转换为三位数

		if (flag == true) {
			// 添加文件类型或文件名作为唯一标识符
			const fileType = file.type || 'unknown'; // 文件类型
			const fileName = file.name || 'unknown'; // 文件名

			return `${year}${month}${day}${hours}${minutes}${seconds}_${milliseconds}_${fileType}_${fileName}`;
		} else
			return `${year}${month}${day}${hours}${minutes}${seconds}_${milliseconds}`;
	}

	function generateTime() {
		const now = new Date();
		const year = now.getFullYear().toString().padStart(4, '0'); // 获取年份并转换为四位数
		const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并转换为两位数
		const day = now.getDate().toString().padStart(2, '0'); // 获取日期并转换为两位数
		const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并转换为两位数
		const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并转换为两位数
		const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒并转换为两位数
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	async function submit() {
		try {
			applicationContent.value.applicationId = generateApplicationId(false);
			applicationContent.value.applicationTime = generateTime();
			console.log("applicationContent", applicationContent.value);

			// 上传身份证图片
			const idCardPromises = image.value.idCard.map(idCardFile => uploadFile(idCardFile, 'idCard'));

			// 上传营业执照图片
			let licensePromise = Promise.resolve();
			if (image.value.license) {
				console.log("上传营业执照");
				licensePromise = uploadFile(image.value.license[0], 'license');
			}

			// 上传附件
			const filePromises = image.value.files.map(file => uploadFile(file, 'file'));

			// 等待所有上传操作完成
			await Promise.all([...idCardPromises, licensePromise, ...filePromises]);

			// 所有上传操作完成后，调用 http.request
			const responseData = await http.request({
				url: "/api/application/insert_application",
				method: "POST",
				data: {
					application: applicationContent.value
				}
			});
			console.log("提交成功", responseData.data);
		} catch (err) {
			// 在这里处理上传文件过程中的错误
			console.log("上传文件失败", err);
		}
	}

	function test() {
		console.log("test", applicationContent.value)
		console.log("golbal", getApp().globalData.openid)
	}
</script>

<style lang="scss" scoped>
	@import "./application.scss";
</style>